package com.argrace.smart.rokid;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.util.Log;

import com.argrace.smart.ArgraceApplication;
import com.argrace.smart.base.ConstantConfigure;

import java.io.IOException;

/**
 * Created by argrace_dev_1 on 2018/2/22.
 */

public class KeePaLiveThread extends Thread {
    boolean is_send = true;
    private String add;
    private int port;
    private String local_add;
    private int local_port;
    KeePaLiveThread(String add, int port,String local_add,int local_port) {
        this.add = add;
        this.port = port;
        this.local_add = local_add;
        this.local_port = local_port;
    }

    @Override
    public void run() {
        super.run();
        SSDPSocket sock = null;
        try {
            while (is_send) {
                sock = new SSDPSocket(add,port,ConstantConfigure.ROKID_KEEPALIVEPROT);
                Log.i("info", "发送心跳中...");
                sock.send(getSSDPDanBoSrt());
                SystemClock.sleep(5000);
                sock.close();
                SystemClock.sleep(5000);
            }
        } catch (Exception e) {
            is_send = false;
            e.printStackTrace();
        }

    }
    private final String SL_NOTIFY = "NOTIFY * HTTP/1.1";
    private final String NEWLINE = "\r\n";
    private final String HOST = "Host:" + "239.255.255.250" + ":" + 1900;
    private String getSSDPDanBoSrt() {
        StringBuilder content = new StringBuilder();
        content.append(SL_NOTIFY).append(NEWLINE);
        content.append(HOST).append(NEWLINE);
        content.append("NT: homebase:device").append(NEWLINE);
        content.append("NTS: ssdp:alive").append(NEWLINE);
        content.append("USN: uuid:" + ArgraceApplication.Device_ID).append(NEWLINE);
        content.append("LOCATION: tcp://" + local_add + ":" + local_port).append(NEWLINE);
        content.append("CACHE-CONTROL: max-age=1800").append(NEWLINE);
        content.append("DEVICE_TYPE: bridge").append(NEWLINE);
        return content.toString();
    }
}
